﻿function CalculateMix() {
    var red = 0;
    var green = 0;
    var blue = 0;
    var count = 0;
    $('.selectedColour').each(function () {
        red = red + parseInt($(this).attr('red'), 10);
        green = green + parseInt($(this).attr('green'), 10);
        blue = blue + parseInt($(this).attr('blue'), 10);
        count = count + 1;
    });
    var mixedColour = 'rgb(' + Math.round(red / count) + ', ' + Math.round(green / count) + ', ' + Math.round(blue / count) + ')';
    $('#mixedColour').css('background', mixedColour);
}

function PickColour(el) {
    $('.noColoursRow').slideUp(250);
    var selectedRgb = 'rgb(' + $(el).attr('red') + ', ' + $(el).attr('green') + ', ' + $(el).attr('blue') + ')';
    var html = '<tr colourId="' + $(el).attr('colourId') + '" red="' + $(el).attr('red') + '" green="' + $(el).attr('green') + '" blue="' + $(el).attr('blue') + '" class="selectedColour"><td><p>' + $(el).attr('man') + '</p><strong>' + $(el).attr('nam') + '</strong><br /><p>' + $(el).attr('code') + '</p></td><td><div style="height: 75px; width: 50px; background: ' + selectedRgb + '"</td></tr>';
    if ($('#componentColours tr').length == 0) {
        $('#componentColours').after(html);
        CalculateMix();
    } else {
        $('#componentColours tr:last').after(html);
        CalculateMix();
    }
}

function RegisterColorPickerEvents() {

    $('#ColourManufacturers').change(function () {
        GetHtml('/order/ColourPickerColours/' + $('#ColourManufacturers').val(), $('#coloursContainer'), function () {
            RegisterColorPickerEvents();
        });
    });

    $('.pickableColour').click(function () {
        PickColour(this);
    });
}